﻿/* 13. *** Write a program that exchanges bits 3, 4 and 5 with bits 24, 25 and 26 of given 32-bit unsigned integer. */

using System;

public class ExchangeThreeBits
{
    public static sbyte startFirstSequence = 3;
    public static sbyte endFirstSequence = 5;

    public static sbyte startSecondSequence = 24;
    public static sbyte endSecondSequence = 26;

    public static uint number;
    public static sbyte bitRight;
    public static sbyte bitLeft;
    public static sbyte firstDirection;
    public static sbyte secondDirection;
    public static sbyte steps;

    public static void Main()
    {
        
        if (DataInput())
            ExchangeBits();
        else
            Console.WriteLine("Invalid Data Input!");
    }

    public static void ExchangeBits()
    {
        for (int step = 0; step < steps; step++)
        {
            bitRight = (number | ((uint)1 << startFirstSequence)) == number ? (sbyte)1 : (sbyte)0;
            bitLeft = (number | ((uint)1 << startSecondSequence)) == number ? (sbyte)1 : (sbyte)0;
            if (bitRight == bitLeft)
            {
                startFirstSequence += firstDirection;
                startSecondSequence += secondDirection;
                continue;
            }
            else if (bitRight == 1)
            {
                number &= ~((uint)1 << startFirstSequence);
                number |= ((uint)1 << startSecondSequence);
            }
            else
            {
                number |= ((uint)1 << startFirstSequence);
                number &= ~((uint)1 << startSecondSequence);
            }

            startFirstSequence += firstDirection;
            startSecondSequence += secondDirection;
        }

        Console.WriteLine("{1}\nnew number = {0}", number, string.Format(Convert.ToString(number, 2).PadLeft(32, '0')));
    }

    public static bool DataInput()
    {
        steps = (sbyte)(Math.Abs(startFirstSequence - endFirstSequence) + 1);

        if ((startFirstSequence > 31) || (endFirstSequence > 31)
            || (startSecondSequence > 31) || (endSecondSequence > 31)
                || (steps - 1 != Math.Abs(startSecondSequence - endSecondSequence)))
        {
            return false;
        }
        else
        {
            Console.Write("number = ");
            number = uint.Parse(Console.ReadLine());
            Console.WriteLine("{0}", string.Format(Convert.ToString(number, 2).PadLeft(32, '0')));

            if (startFirstSequence <= endFirstSequence)
                firstDirection = 1;
            else
                firstDirection = -1;

            if (startSecondSequence <= endSecondSequence)
                secondDirection = 1;
            else
                secondDirection = -1;

            return true;
        }
    }
}